
package com.oos.zone.wechat.mp.controller;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 功能描述：
 *
 * @author 拓金辉
 * @version 1.0
 * @date 2021-08-01 16:29:46
 */
@RestController
public class WxMpAuthorizationController {

    @Resource
    private Executor executor;

    @Resource
    private WxMpService wxMpService;

    /**
     * 方法描述：公众号微信登录授权
     *
     * @author 拓金辉
     * @date 2021-08-01 22:32:30
     */
    @GetMapping(value = "/redirectAuthorizationUrl")
    public void redirectAuthorizationUrl(HttpServletResponse response) throws IOException {
        String redirectAuthorizationUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(
                "http://101.132.238.80/oauth2CodeCallBack", WxConsts.OAuth2Scope.SNSAPI_USERINFO, "");
        response.sendRedirect(redirectAuthorizationUrl);
    }

    /**
     * 方法描述：公众号授权码回调
     *
     * @param code  授权码
     * @param state 重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     * @author 拓金辉
     * @date 2021-08-08 09:42:19
     */
    @GetMapping(value = "/oauth2CodeCallBack")
    public void oauth2CodeCallBack(@RequestParam(value = "code") String code,
                                   @RequestParam(value = "state", required = false) String state) throws WxErrorException {
        WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, "zh_CN");
        CompletableFuture.runAsync(() -> handlerUserInfo(userInfo, state), executor);
    }

    /**
     * 方法描述：业务处理用户信息
     *
     * @param userInfo 用户信息
     * @param state    重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     * @author 拓金辉
     * @date 2021-08-08 09:43:25
     */
    private void handlerUserInfo(WxOAuth2UserInfo userInfo, String state) {
        // TODO 此处业务处理用户信息
    }

}
